<template>
  <div class="teacher-manage">
    <div class="page-header">
      <h2>教师管理</h2>
      <el-button type="primary" @click="handleAdd">
        <el-icon><Plus /></el-icon> 添加教师
      </el-button>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-container">
      <el-input
        v-model="searchQuery"
        placeholder="搜索教师"
        class="filter-item search-input"
        @input="handleFilter"
        clearable
      >
        <template #prefix>
          <el-icon><Search /></el-icon>
        </template>
      </el-input>

      <el-select v-model="departmentFilter" placeholder="所属院系" clearable @change="handleFilter" class="filter-item">
        <el-option label="全部院系" value="" />
        <el-option v-for="dept in departments" :key="dept.id" :label="dept.name" :value="dept.id" />
      </el-select>

      <el-select v-model="titleFilter" placeholder="职称" clearable @change="handleFilter" class="filter-item">
        <el-option label="全部职称" value="" />
        <el-option v-for="title in titles" :key="title" :label="title" :value="title" />
      </el-select>
    </div>

    <!-- 教师列表 -->
    <el-table
      v-loading="loading"
      :data="teacherList"
      border
      style="width: 100%"
    >
      <el-table-column prop="id" label="ID" width="80" />
      <el-table-column prop="username" label="用户名" width="120" />
      <el-table-column prop="name" label="姓名" min-width="120" />
      <el-table-column prop="gender" label="性别" width="80">
        <template #default="scope">
          {{ scope.row.gender === 1 ? '男' : '女' }}
        </template>
      </el-table-column>
      <el-table-column prop="title" label="职称" width="120" />
      <el-table-column prop="departmentId" label="所属院系" width="180">
        <template #default="scope">
          {{ getDepartmentName(scope.row.departmentId) }}
        </template>
      </el-table-column>
      <el-table-column prop="email" label="邮箱" min-width="180" />
      <el-table-column prop="phone" label="电话" width="140" />
      <el-table-column prop="status" label="状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
            {{ scope.row.status === 1 ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button 
            size="small" 
            type="danger" 
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="page.current"
        v-model:page-size="page.size"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="page.total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>

    <!-- 教师表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '添加教师' : '编辑教师'"
      width="650px"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" :disabled="dialogType === 'edit'" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="form.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogType === 'add'">
          <el-input v-model="form.password" type="password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="form.gender">
            <el-radio :label="1">男</el-radio>
            <el-radio :label="2">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="职称" prop="title">
          <el-select v-model="form.title" placeholder="请选择职称">
            <el-option v-for="title in titles" :key="title" :label="title" :value="title" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属院系" prop="departmentId">
          <el-select v-model="form.departmentId" placeholder="请选择所属院系">
            <el-option v-for="dept in departments" :key="dept.id" :label="dept.name" :value="dept.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入电话" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="正常"
            inactive-text="停用"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import { getTeacherList, getTeacherById, addTeacher, updateTeacher, deleteTeacher } from '@/api/teacher'

// 加载状态
const loading = ref(false)

// 教师列表数据
const teacherList = ref([])

// 筛选条件
const searchQuery = ref('')
const departmentFilter = ref('')
const titleFilter = ref('')

// 分页参数
const page = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // add 或 edit
const formRef = ref()
const form = reactive({
  id: null,
  username: '',
  name: '',
  password: '',
  gender: 1,
  title: '',
  departmentId: null,
  email: '',
  phone: '',
  status: 1
})

// 表单验证规则
const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不少于 6 个字符', trigger: 'blur' }
  ],
  gender: [
    { required: true, message: '请选择性别', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请选择职称', trigger: 'change' }
  ],
  departmentId: [
    { required: true, message: '请选择所属院系', trigger: 'change' }
  ],
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }
  ]
}

// 院系列表
const departments = ref([
  { id: 1, name: '计算机科学与技术学院' },
  { id: 2, name: '数学学院' },
  { id: 3, name: '物理学院' },
  { id: 4, name: '电子信息学院' },
  { id: 5, name: '经济管理学院' }
])

// 职称列表
const titles = ref(['讲师', '副教授', '教授', '助教'])

// 获取院系名称
const getDepartmentName = (departmentId) => {
  const dept = departments.value.find(d => d.id === departmentId)
  return dept ? dept.name : '-'
}

// 初始化数据
onMounted(() => {
  fetchTeachers()
})

// 获取教师列表
const fetchTeachers = async () => {
  loading.value = true
  try {
    const params = {
      page: page.current,
      size: page.size,
      departmentId: departmentFilter.value || undefined,
      title: titleFilter.value || undefined,
      keyword: searchQuery.value || undefined
    }
    const res = await getTeacherList(params)
    teacherList.value = res.data.records
    page.total = res.data.total
  } catch (error) {
    console.error('获取教师列表失败', error)
    ElMessage.error('获取教师列表失败')
  } finally {
    loading.value = false
  }
}

// 筛选处理
const handleFilter = () => {
  page.current = 1
  fetchTeachers()
}

// 分页处理
const handleSizeChange = (size) => {
  page.size = size
  fetchTeachers()
}

const handleCurrentChange = (current) => {
  page.current = current
  fetchTeachers()
}

// 添加教师
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑教师
const handleEdit = async (row) => {
  dialogType.value = 'edit'
  resetForm()
  
  try {
    const res = await getTeacherById(row.id)
    Object.assign(form, res.data)
    dialogVisible.value = true
  } catch (error) {
    console.error('获取教师详情失败', error)
    ElMessage.error('获取教师详情失败')
  }
}

// 删除教师
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要删除教师 ${row.name} 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      await deleteTeacher(row.id)
      ElMessage.success('删除成功')
      fetchTeachers()
    } catch (error) {
      console.error('删除教师失败', error)
      ElMessage.error('删除教师失败')
    }
  }).catch(() => {})
}

// 重置表单
const resetForm = () => {
  if (formRef.value) {
    formRef.value.resetFields()
  }
  
  Object.assign(form, {
    id: null,
    username: '',
    name: '',
    password: '',
    gender: 1,
    title: '',
    departmentId: null,
    email: '',
    phone: '',
    status: 1
  })
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        if (dialogType.value === 'add') {
          await addTeacher(form)
          ElMessage.success('添加成功')
        } else {
          await updateTeacher(form)
          ElMessage.success('更新成功')
        }
        dialogVisible.value = false
        fetchTeachers()
      } catch (error) {
        console.error('保存教师失败', error)
        ElMessage.error('保存教师失败')
      }
    }
  })
}
</script>

<style scoped>
.teacher-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.filter-container {
  display: flex;
  margin-bottom: 20px;
  gap: 15px;
}

.filter-item {
  margin-right: 10px;
}

.search-input {
  width: 260px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}
</style> 